﻿using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class PrefabHelper
{
    class ABMission
    {
        public string url;
        public string path;
        public event  Action<object> callBack;
        public void Start()
        {
            AssetBundleCreateRequest abcr = AssetBundle.LoadFromFileAsync(path);
            abcr.completed += (o) => {
                AssetBundleCreateRequest a = o as AssetBundleCreateRequest;
                UnityEngine.Object obj = a.assetBundle.LoadAsset(url);
                if (obj != null)
                {
                    if (callBack != null)
                        callBack(obj);
                }
            };
        }
    }
    static List<ABMission> missions = new List<ABMission>();
    public static void LoadPrefab(string url, Action<object> callBack)
    {
#if UNITY_EDITOR
        if (LoadFromAssets(url, callBack))
            return;
#endif
        if (LoadFromResources(url, callBack))
            return;
        LoadFromAB(url, callBack);
    }
#if UNITY_EDITOR
    static bool LoadFromAssets(string url, Action<object> callBack)
    {
        string path = "Assets/GameAssets/" + url;
        if (File.Exists(path))
        {
            UnityEngine.Object obj = UnityEditor.AssetDatabase.LoadMainAssetAtPath(path);
            if (callBack != null)
                callBack(obj);
            return true;
        }
        return false;
    }
#endif
    static bool LoadFromResources(string url,Action<object> callBack)
    {
        UnityEngine.Object obj = Resources.Load(url);
        if(obj!=null)
        {
            if (callBack != null)
                callBack(obj);
            return true;
        }
        return false;
    }
    static bool LoadFromAB(string url, Action<object> callBack)
    {
        var bundles = AssetBundle.GetAllLoadedAssetBundles();
        foreach(var ab in bundles)
        {
            if(ab.name==url)
            {
                UnityEngine.Object obj = ab.LoadAsset(url);
                if (obj != null)
                {
                    if (callBack != null)
                        callBack(obj);
                }
                return true;
            }
        }
        for(int i=0;i<missions.Count;i++)
        {
            if(missions[i].url==url)
            {
                missions[i].callBack += callBack;
                return true;
            }
        }
        string path = AssetsVersionControl.GetAssetsPath(url);
        if (path == "")
            return false;
        ABMission mission = new ABMission();
        mission.url = url;
        mission.path = path;
        mission.callBack += callBack;
        mission.Start();
        return true;
    }
}
